<template>
  <view-template>
    <template #content>
      <scroll-view
        :refresher-enabled="true"
        @scrolltolower="triggerBottom"
        :scroll-y="true"
        class="list"
        @refresherrefresh="refreshList"
        :refresher-triggered="refresherTriggered"
      >
        <view class="delivery-order-list">
          <delivery-order-component
            v-for="deliveryOrder in listState.list"
            :key="deliveryOrder.id"
            :delivery-order="deliveryOrder"
            :is-grabbing-order="false"
          >
            <template #control>
              <button
                class="take-order-button"
                :class="{ disable: deliveryOrder.canPickUpSecond != null }"
                @click="reportToShop(deliveryOrder)"
                v-if="
                  deliveryOrder.deliveryState === DeliveryOrderState.RIDER_RECEIVED_ORDER ||
                  (deliveryOrder.canPickUpSecond ?? 0 > 0)
                "
              >
                上报到店<span v-show="deliveryOrder.canPickUpSecond != null"
                  >({{ deliveryOrder.canPickUpSecond }}s)</span
                >
              </button>
              <button class="take-order-button" @click="confirmMealPickup(deliveryOrder)" v-else>确认取餐</button>
            </template>
          </delivery-order-component>
        </view>
      </scroll-view>
    </template>
    <template #control>
      <view-bottom-control :is-right-button-active="false" @un-active-click="refreshList">
        <template #right-active-icon="{ size }">
          <uni-icons type="arrow-up" :size="size"></uni-icons>
        </template>
      </view-bottom-control>
    </template>
  </view-template>
</template>

<script setup lang="ts">
import ViewTemplate from '../../components/view-template/index.vue'
import ViewBottomControl from '../../components/view-bottom-control/index.vue'
import { ref, computed } from 'vue'
import $store from '@/store'
import $API from '@/api'
import type { WaitPickingDeliveryOrder } from '@/types/response/delivery-order'
import { TimeOperations } from '@/utils/TimeUtils'
import DeliveryOrderComponent from '../../components/delivery-order/index.vue'
import { $modal } from '@/plugins'
import { DeliveryOrderState } from '@/enum'
import type DeliveryOrder from '@/types/entity/DeliveryOrder'
import { countdown } from '@/utils/countdownEventHandler'
import { nextTick } from 'vue'
const refresherTriggered = ref(false)
// // 骑手上线
// const confirmDialogRef = ref()
function goOnLine() {
  // 触发骑手上线事件
  $store.user.workStatusChangeEvent.emit(1)
}
// 获取附近配送单
const listState = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  list: [] as WaitPickingDeliveryOrder[]
})
// 从列表中移除某项
function removeDeliveryOrderFormList(deliveryOrder: DeliveryOrder) {
  const list = listState.value.list
  for (let [index, item] of list.entries()) {
    if (item === deliveryOrder) {
      list.splice(index, 1)
    }
  }
}
// 加载当前页参数的附近配送单
async function loadNearbyDeliveryList() {
  const result = await $API.deliveryOrder.riderWaitPickingPage({
    currentPage: listState.value.currentPage,
    pageSize: listState.value.pageSize
  })
  if (!result.success) return

  listState.value.total = result.data.total
  listState.value.list.push(...result.data.list)
  nextTick(() => {
    listState.value.list.forEach((deliveryOrder) => {
      if (
        deliveryOrder.deliveryState !== DeliveryOrderState.RIDER_ARRIVED_STORE ||
        Date.now() > (deliveryOrder.canPickUpTimeStamp ?? 0)
      )
        return
      deliveryOrder.canPickUpSecond = Math.ceil((deliveryOrder.canPickUpTimeStamp! - Date.now()) / 1000)
      setCountdown(deliveryOrder)
    })
  })
}
// 初始化
loadNearbyDeliveryList()

// 重置加载
const isLoading = ref(false)
async function refreshList() {
  if (isLoading.value) return
  isLoading.value = true
  refresherTriggered.value = true
  // 重置参数
  listState.value.currentPage = 1
  listState.value.list = []
  // 加载列表数据
  try {
    await loadNearbyDeliveryList()
  } finally {
    refresherTriggered.value = false
    isLoading.value = false
  }
}
// 触发骑手接新单-刷新列表
$store.order.onReceivingNewOrder.on(() => refreshList())
// 触底
async function triggerBottom() {
  const nextPage = listState.value.currentPage + 1
  const totalPage = Math.ceil(listState.value.total / listState.value.pageSize)
  if (nextPage > totalPage) return
  listState.value.currentPage = nextPage
  loadNearbyDeliveryList()
}
// 设置倒计时
function setCountdown(deliveryOrder: WaitPickingDeliveryOrder) {
  countdown(
    deliveryOrder.canPickUpSecond ?? 0,
    (currentTime) => (deliveryOrder.canPickUpSecond = currentTime),
    () => {
      deliveryOrder.canPickUpSecond = undefined
      deliveryOrder.deliveryState = DeliveryOrderState.RIDER_ARRIVED_STORE
    }
  )
}
// 骑手尝试抢单
async function reportToShop(deliveryOrder: WaitPickingDeliveryOrder) {
  const result = await $API.deliveryOrder.reportToShop(deliveryOrder.id)
  // result.data 是剩余可点击取餐的秒
  if (result.success) {
    // 进行倒计时->倒计时结果->点击已取餐
    deliveryOrder.canPickUpSecond = result.data
    setCountdown(deliveryOrder)
  } else {
    $modal.toastErrorMsg(result.message)
  }
}
async function confirmMealPickup(deliveryOrder: WaitPickingDeliveryOrder) {
  const result = await $API.deliveryOrder.confirmMealPickup(deliveryOrder.id)
  if (result.success) {
    $modal.toastSuccessMsg('取餐成功！')
    removeDeliveryOrderFormList(deliveryOrder)
    // 触发骑手已取餐事件
    $store.order.onRiderPickingUpMeal.emit()
  } else {
    $modal.toastErrorMsg(result.message)
  }
}
</script>

<style scoped lang="scss">
.list {
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  $delivery-order-distance: 15px;

  .delivery-order-list {
    padding: 0rpx 20rpx;
    padding-bottom: $delivery-order-distance;
  }

  .take-order-button {
    display: block;
    width: 100%;
    height: 40px;
    font-size: 33rpx;
    border-radius: 5px;
    text-align: center;
    color: #fff;
    background: linear-gradient(
      90deg,
      rgb(29 28 25) 0%,
      rgb(255 153 0 / 100%) 0%,
      rgb(254 70 1 / 100%) 100%,
      rgb(254 70 1 / 100%) 100%
    );
    line-height: 40px;
  }

  .disable {
    color: #aaa !important;
    background: rgb(242 242 242 / 100%) !important;
  }
}
</style>
